<template>
    <a-drawer :width="700" title="选择施工工艺" placement="right" v-model:visible="open">
        <!-- <a-button style="width: 100%;">添加辅助工具</a-button> -->
        <a-form :model="form" name="basic" :label-col="{ span: 8 }">
            <a-row>
                <a-col :span="12">
                    <a-form-item label="选择工艺类型" name="craftType">
                        <a-select v-model:value="form.craftType" mode="multiple" :disabled="craftChoose"
                            placeholder="请选择工艺类型" style="width: 450px">
                            <a-select-option v-for="item of craftData" :key="item">{{ item }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="12">
                    <a-form-item label="选择仪器系列" name="instrumentType">
                        <a-select v-model:value="form.instrumentType" mode="multiple" :disabled="instrumentChoose"
                            placeholder="选择仪器系列" style="width: 450px">
                            <a-select-option v-for="item of instrumentData" :key="item">{{ item }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <!-- <a-row>
                <a-col :span="12">
                    <a-form-item label="选择电缆" name="cableType">
                        <a-select v-model:value="form.cableType" placeholder="选择电缆" style="width: 450px">
                            <a-select-option v-for="item of cableData" :key="item.cableId">
                                {{ item.cableId + '（' + item.manufacturer + '）' }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row> -->
            <a-row>
                <a-button v-if="!submitChoice" style="width: 560px;" type="primary" ghost block :disabled="submitChoice"
                    @click="modifyChoose">
                    <EditOutlined />修改
                </a-button>
                <a-button v-if="submitChoice" style="width: 560px;" type="primary" block :disabled="!submitChoice"
                    @click="submitChoose">
                    <UploadOutlined />提交
                </a-button>
            </a-row>
            <a-divider></a-divider>
            <a-row>
                <a-col :span="12">
                    <a-form-item label="选择工艺工具" name="auxiliaryList">
                        <a-button type="primary" ghost style="width: 450px" @click="openToolModal">
                            <AppstoreAddOutlined />添加工艺工具
                        </a-button>
                    </a-form-item>

                    <AntdConfirmModal title="添加工艺工具" ref="modalRef" width="800px" @confirm="submitCreateForm">
                        <a-row>
                            <a-select ref="select" v-model:value="form.auxiliaryTool" style="width: 120px" @focus="focus">
                                <a-select-option value="eccentric">偏心器</a-select-option>
                                <a-select-option value="rubber">橡胶扶正器</a-select-option>
                                <a-select-option value="mental">金属扶正器</a-select-option>
                            </a-select>
                        </a-row>
                        <a-divider></a-divider>
                        <eccentric-popup v-if="form.auxiliaryTool === 'eccentric'"
                            @eccentricSelection="eccentricSelection"></eccentric-popup>
                        <rubber-popup v-if="form.auxiliaryTool === 'rubber'"
                            @rubberSelection="rubberSelection"></rubber-popup>
                        <mental-popup v-if="form.auxiliaryTool === 'mental'"
                            @mentalSelection="mentalSelection"></mental-popup>
                    </AntdConfirmModal>
                </a-col>
            </a-row>
            <a-row>
                <a-table style="width: 100%;" :dataSource="params.auxiliaryList" size="small" :columns="columns" bordered>
                    <template #bodyCell="{ column, text, record }">
                        <template v-if="['numbers'].includes(column.dataIndex)">
                            <div>
                                <a-input-number v-if="editableData[record.auxiliaryToolId]"
                                    v-model:value="editableData[record.auxiliaryToolId][column.dataIndex]" :min="1"
                                    style="margin: -5px 0" />
                                <template v-else>
                                    {{ text }}
                                </template>
                            </div>
                        </template>
                        <template v-else-if="column.dataIndex === 'operation'">
                            <div style="margin-right: 8px;">
                                <span v-if="editableData[record.auxiliaryToolId]">
                                    <a-button type="link" @click="save(record.auxiliaryToolId)">保存 </a-button>
                                    <AntdZh><a-popconfirm title="取消编辑 ?" @confirm="cancel(record.auxiliaryToolId)">
                                        <a-button type="link">取消</a-button>
                                    </a-popconfirm></AntdZh>
                                </span>
                                <span v-else>
                                    <a-button type="link" @click="edit(record.auxiliaryToolId)">编辑</a-button>
                                    <AntdZh><a-popconfirm title="确定删除该条记录 ?" @confirm="del(record.auxiliaryToolId)">
                                        <a-button type="link" danger>删除</a-button>
                                    </a-popconfirm></AntdZh>
                                </span>
                            </div>
                        </template>
                    </template>
                </a-table>
            </a-row>
        </a-form>
    </a-drawer>
</template>
<script setup>
import { cloneDeep } from 'lodash-es';
import { EditOutlined, UploadOutlined, AppstoreAddOutlined } from '@ant-design/icons-vue';
import { craftList, instrumentList } from '../../tool/craft'
import EccentricPopup from '../../tool/type/EccentricPopup'
import RubberPopup from '../../tool/type/RubberPopup'
import MentalPopup from '../../tool/type/MentalPopup'
import { queryList } from "@/api/tool/cable.js";
import DesignScheme from '@/api/design/schemes.js'
import useApp from "@/hooks";
const { $, proxy } = useApp();
const craftDatas = ref(craftList)
const craftData = Object.values(craftDatas.value).map(item => item.name);
const instrumentDatas = ref(instrumentList)
const instrumentData = Object.values(instrumentDatas.value).map(item => item.name)
const cableData = ref()
const modalRef = ref(null)
const open = ref(false)
const editableData = reactive({});
const params = reactive({
    processType: '',
    auxiliaryList: [], //
    instrumentSeries: '', //仪器系列
})
const form = ref({
    craftType: [], //工艺类型
    instrumentType: [], //仪器类型
    cableType: undefined, //电缆类型
    auxiliaryTool: 'eccentric', //?
    pullingType: undefined, //拉力棒
})
const craftChoose = ref(false)
const instrumentChoose = ref(false)
const submitChoice = ref(true)
const number = ref(1)
const columns = [
    {
        title: '型号',
        dataIndex: 'auxiliaryToolId',
        key: 'auxiliaryToolId',
        width: '25%'
    },
    {
        title: '名称',
        dataIndex: 'auxiliaryToolName',
        key: 'auxiliaryToolName',
        width: '35%'
    },
    {
        title: '数量',
        dataIndex: 'numbers',
        key: 'numbers',
        width: '15%'
    },
    {
        title: '操作',
        dataIndex: 'operation',
    }
];
const data = ref([])
const eccentricData = ref([]) //偏心器
function eccentricSelection(e) {
    eccentricData.value = e
}
const rubberData = ref([]) //橡胶扶正器
function rubberSelection(e) {
    rubberData.value = e
}
const mentalData = ref([]) //金属扶正器
function mentalSelection(e) {
    mentalData.value = e
}
// 编辑
const edit = key => {
    editableData[key] = cloneDeep(params.auxiliaryList.filter(item => key === item.auxiliaryToolId)[0]);
};
// 取消
const cancel = key => {
    delete editableData[key];
};
// 删
const del = key => {
    params.auxiliaryList = params.auxiliaryList.filter(item => item.auxiliaryToolId !== key);
    let schemeId = localStorage.getItem("schemeId");
    DesignScheme.updateOne(schemeId, params).then(res => {
        // console.log('updateOne', res)
        // localStorage.setItem("schemeId", res.id)
        $.showToast({
            title: '删除成功',
            icon: 'success'
        })
        getToolList()
    })
};
// 保存
const save = key => {
    console.log('editableData[key]', key, editableData[key]);
    params.auxiliaryList = params.auxiliaryList.map(item => {
        if (item.auxiliaryToolId === key) {
            item = editableData[key]
        }
        return item;
    });

    let schemeId = localStorage.getItem("schemeId");
    DesignScheme.updateOne(schemeId, params).then(res => {
        // console.log('save', res);
        // localStorage.setItem("schemeId", res.id)
        $.showToast({
            title: '修改成功',
            icon: 'success'
        })
        getToolList()
        delete editableData[key];
    })
};
// 工艺类型/系列 提交
function submitChoose() {
    params.processType = form.value.craftType.join(',')
    params.instrumentSeries = form.value.instrumentType.join(',')
    console.log('submitChoose', params.processType, params.instrumentSeries);

    let schemeId = localStorage.getItem("schemeId");
    DesignScheme.updateOne(schemeId, params).then(res => {
        // console.log('updateOne', res)
        // localStorage.setItem("schemeId", res.id)
        $.showToast({
            title: '提交成功',
            icon: 'success'
        })
        seekChoose()
        submitChoice.value = false
    })
}
// 工艺类型/系列 修改
function modifyChoose() {
    craftChoose.value = false
    instrumentChoose.value = false
    submitChoice.value = true
}
// 工艺类型/系列 查找
function seekChoose() {
    let schemeId = localStorage.getItem("schemeId");
    if (!schemeId) {
        console.log('schemeId为空');
    } else {
        DesignScheme.getDataOne(schemeId).then(res => {
            if (res.processType) {
                form.value.craftType = res.processType.split(",")
                craftChoose.value = true
            }
            if (res.instrumentSeries) {
                form.value.instrumentType = res.instrumentSeries.split(",")
                instrumentChoose.value = true
            }
            // 修改、提交按钮的判断
            if (!(res.processType === "") || !(res.instrumentSeries === "")) {
                submitChoice.value = false
            } else {
                submitChoice.value = true
            }
        })
    }
}
seekChoose()

// 工艺工具添加 提交
function submitCreateForm() {
    data.value = [...eccentricData.value, ...rubberData.value, ...mentalData.value]
    console.log('data.value', data.value);
    data.value.forEach((item, index) => {
        console.log('item', item);
        console.log('params.auxiliaryList', params.auxiliaryList);
        const found = params.auxiliaryList.find((element) => (item.alignmentModelId || item.eccentricModelId) === element.auxiliaryToolId);
        if (found) {
            found.numbers++
            params.auxiliaryList.forEach((item, index) => {
                if (found.auxiliaryToolId === item.auxiliaryToolId) {
                    item.auxiliaryToolId = found.auxiliaryToolId
                    item.auxiliaryToolName = found.auxiliaryToolName
                    item.numbers = found.numbers
                }
            })
        } else {
            params.auxiliaryList.push({
                auxiliaryToolId: item.alignmentModelId || item.eccentricModelId,
                auxiliaryToolName: item.alignmentName || item.eccentricName,
                numbers: 1
            });
        }
    });
    console.log('params.auxiliaryList', params.auxiliaryList);

    let schemeId = localStorage.getItem("schemeId");
    DesignScheme.updateOne(schemeId, params).then(res => {
        // console.log('updateOne', res)
        // localStorage.setItem("schemeId", res.id)
        $.showToast({
            title: '添加成功',
            icon: 'success'
        })
        getToolList()
        resetNul()
    })
    modalRef.value.closeModal()
}
// 施工工艺详情 查询
function getToolList() {
    let schemeId = localStorage.getItem("schemeId");
    if (!schemeId) {
        console.log('schemeId为空');
    } else {
        DesignScheme.getDataOne(schemeId).then(res => {
            console.log('getToolList', res);
            if (res.auxiliaryList !== null) {
                params.auxiliaryList = res.auxiliaryList
            }
            params.instrumentSeries = res.instrumentSeries
            console.log('getToolList--params', params);
            // 修改、提交按钮的判断
            if ((res.processType === "" || res.processType == null) && (res.instrumentSeries === "" || res.instrumentSeries == null)) {
                submitChoice.value = true
            } else {
                submitChoice.value = false
            }
        })
    }
}
getToolList()
// 工艺工具重置
function resetNul() {
    data.value = []
    eccentricData.value = []
    rubberData.value = []
    mentalData.value = []
}

// function getlistCable() {
//     let query = { pageNum: 1, pageSize: 100, sortBy: 'id', searchKey: '' };
//     queryList(query).then(res => {
//         cableData.value = res.content
//         console.log(cableData.value)
//     })
// }
// getlistCable()

function openToolModal() {
    modalRef.value.openModal()
}
function openDrawer() {
    open.value = true;
}
defineExpose({
    openDrawer: openDrawer
})
</script>